const axios = require('axios');
const fs = require('fs');
const path = require('path');

// 配置请求基础路径
const BASE_URL = 'http://localhost:3000/api';

// 管理员登录并获取token
async function loginAdmin() {
  try {
    const response = await axios.post(`${BASE_URL}/admin/login`, {
      username: 'admin',
      password: 'admin123'
    });
    
    if (response.data && response.data.token) {
      console.log('管理员登录成功，获取到token');
      return response.data.token;
    } else {
      console.error('登录成功但未返回token:', response.data);
      return null;
    }
  } catch (error) {
    console.error('管理员登录失败:', error.response?.data || error.message);
    return null;
  }
}

// 测试删除商品功能
async function testDeleteGoods() {
  // 测试结果对象
  const testResult = {
    success: false,
    message: '',
    steps: []
  };

  try {
    // 1. 检查服务器状态
    testResult.steps.push({ step: '检查服务器状态', status: '开始' });
    const serverResponse = await axios.get(`${BASE_URL}/goods`);
    if (serverResponse.status === 200) {
      testResult.steps[0].status = '成功';
      testResult.steps[0].message = '服务器运行正常';
    } else {
      testResult.steps[0].status = '失败';
      testResult.steps[0].message = `服务器状态异常: ${serverResponse.status}`;
      throw new Error('服务器状态异常');
    }

    // 2. 获取管理员token
    testResult.steps.push({ step: '获取管理员token', status: '开始' });
    const token = await loginAdmin();
    if (!token) {
      testResult.steps[1].status = '失败';
      testResult.steps[1].message = '无法获取管理员token';
      throw new Error('无法获取管理员token，测试终止');
    }
    testResult.steps[1].status = '成功';

    // 3. 创建一个测试商品用于删除
    testResult.steps.push({ step: '创建测试商品', status: '开始' });
    // 使用唯一标识的标题，确保这是一个全新的商品
    const uniqueTitle = `测试删除商品_${Date.now()}`;
    const createResponse = await axios.post(`${BASE_URL}/admin/goods`, 
      {
        title: uniqueTitle,
        description: '这个商品用于测试删除功能',
        price: 99.99,
        image: '/test.jpg',
        tag: '测试',
        details: '测试商品详细信息',
        specifications: [{ name: '测试', value: '测试值' }]
      },
      {
        headers: { 'Authorization': `Bearer ${token}` }
      }
    );
    
    if (createResponse.data && createResponse.data.success) {
      testResult.steps[2].status = '成功';
      testResult.steps[2].message = `创建商品成功，商品ID: ${createResponse.data.data.id}`;
      const testGoodsId = createResponse.data.data.id;
      console.log(`创建了测试商品，ID: ${testGoodsId}`);

      // 4. 验证该商品没有关联订单
      testResult.steps.push({ step: '验证商品无关联订单', status: '开始' });
      // 为了简化测试，我们假设新创建的商品不会有订单关联
      testResult.steps[3].status = '成功';

      // 5. 测试删除商品
      testResult.steps.push({ step: '删除测试商品', status: '开始' });
      console.log(`尝试删除商品，ID: ${testGoodsId}`);
      try {
        const deleteResponse = await axios.delete(`${BASE_URL}/admin/goods/${testGoodsId}`, {
          headers: { 'Authorization': `Bearer ${token}` },
          validateStatus: false // 不抛出非2xx状态码的错误
        });
        
        console.log(`删除商品API返回状态码: ${deleteResponse.status}`);
        console.log(`删除商品API返回数据:`, deleteResponse.data);
        
        if (deleteResponse.data && deleteResponse.data.success) {
          testResult.steps[4].status = '成功';
          testResult.steps[4].message = `删除商品成功，商品ID: ${testGoodsId}`;
          testResult.success = true;
          testResult.message = '商品删除功能测试成功';
        } else {
          testResult.steps[4].status = '失败';
          testResult.steps[4].message = `删除商品失败: ${deleteResponse.data?.message || '未知错误'}`;
          throw new Error(`删除商品失败: ${deleteResponse.data?.message || '未知错误'}`);
        }
      } catch (error) {
        console.error('删除商品请求异常:', error);
        console.error('错误详情:', error.response?.data);
        testResult.steps[4].status = '失败';
        testResult.steps[4].message = `删除商品请求异常: ${error.message}`;
        throw error;
      }
    } else {
      testResult.steps[2].status = '失败';
      testResult.steps[2].message = `创建商品失败: ${createResponse.data?.message || '未知错误'}`;
      throw new Error('创建测试商品失败');
    }
  } catch (error) {
    testResult.success = false;
    testResult.message = `测试失败: ${error.message}`;
    console.error('测试失败:', error.message);
  } finally {
    // 保存测试结果到文件
    const resultPath = path.join(__dirname, 'test_results.json');
    fs.writeFileSync(resultPath, JSON.stringify(testResult, null, 2));
    console.log('测试结果已保存到:', resultPath);
    
    // 输出测试摘要
    console.log('\n===== 测试摘要 =====');
    console.log(`整体结果: ${testResult.success ? '✅ 成功' : '❌ 失败'}`);
    console.log(`消息: ${testResult.message}`);
    console.log('==================');
  }
}

// 运行测试
console.log('开始测试商品删除功能...');
testDeleteGoods().then(() => {
  console.log('测试完成');
}).catch(err => {
  console.error('测试过程中出现错误:', err);
});